<template>
    <div>
        <div class="btns" v-show="showPrintBtns">
            <!-- <el-button
                type="primary"
                size="small"
                class="pdf-button"
                @click="getPdf('pdfDom')"
            >导出为PDF</el-button> -->
            <el-button
                type="primary"
                size="small"
                class="print-button"
                @click="toPrint()"
                >打印</el-button
            >
        </div>

        <div class="container-narrow" id="pdfDom">
            <div class="watermark-div">
                <!--一56个水印可以恰好覆盖一整页-->
                <div v-for="i in 56" :key="i" class="watermark">
                    {{ templateInfo.infoWatermark }}
                </div>
            </div>
            <el-row class="text-mini">
                <el-col :span="12">
                    <span>{{ currentTime }}</span>
                </el-col>
            </el-row>
            <!-- Header -->
            <el-row style="margin-top: 20px; min-height: 60px">
                <el-col :span="8" :offset="8">
                    <img
                        :src="templateInfo.infoImageUrl"
                        style="height: 60px; width: 100%"
                        alt=""
                    />
                </el-col>
            </el-row>
            <h3 style="text-align: center">
                {{ templateInfo.infoInstitutionName }}
            </h3>
            <el-row>
                <h5 style="text-align: center">{{ templateInfo.infoTitle }}</h5>
            </el-row>
            <el-row>
                <el-col :span="10" :offset="14">
                    <h4 style="color: rgb(217, 149, 148)">
                        病理号：{{ this.$route.params.pid }}
                    </h4>
                </el-col>
            </el-row>
            <hr />
            <el-row style="margin-top: 12px; font-size: 15px; height: 740px">
                <grid-layout
                    :layout.sync="componentList"
                    :col-num="templateCol ? templateCol : 12"
                    :row-height="24"
                    :is-draggable="false"
                    :is-resizable="false"
                    :is-mirrored="false"
                    :vertical-compact="true"
                    :use-css-transforms="true"
                >
                    <grid-item
                        v-for="(item, index) in componentList"
                        :x="item.x"
                        :y="item.y"
                        :w="item.w"
                        :h="item.h"
                        :i="item.i"
                        :key="index"
                    >
                        <el-row
                            v-if="item.smallType === 'space'"
                            class="row-in-grid-item"
                        ></el-row>

                        <hr v-else-if="item.smallType === 'hr'" />

                        <el-row
                            v-else-if="item.smallType === 'text'"
                            class="row-in-grid-item"
                        >
                            <span :style="styleString(item.styleJson)">
                                {{ item.stringContent }}
                            </span>
                        </el-row>

                        <el-row
                            v-else-if="item.smallType === 'input'"
                            class="row-in-grid-item"
                        >
                            <span :style="styleString(item.styleJson)">
                                {{ opinionJson[item.i] }}
                            </span>
                        </el-row>

                        <el-row
                            v-else-if="item.smallType === 'selection'"
                            class="row-in-grid-item"
                        >
                            <span :style="styleString(item.styleJson)">
                                {{ opinionJson[item.i] }}
                            </span>
                        </el-row>

                        <el-row
                            v-else-if="item.smallType === 'special'"
                            class="row-in-grid-item"
                        >
                            <!--病理图像判断-->
                            <div
                                v-if="
                                    item.i === 'special_normal_pathologyFiles'
                                "
                                style="width: 100%; height: 100%"
                            >
                                <span style="float: left">{{
                                    item.stringContent
                                }}</span>
                                <img
                                    v-for="(pic, index) in annotationList"
                                    class="diagnose-img"
                                    style="float: left"
                                    :key="index"
                                    alt=""
                                    :src="pic.imgUrl"
                                    @click="OpenImage(pic.imgUrl)"
                                />
                            </div>
                            <!--签名图像-->
                            <div
                                v-else-if="
                                    item.i === 'special_base_reportDoctor'
                                "
                            >
                                <span>{{ item.stringContent }}</span>
                            </div>
                        </el-row>
                    </grid-item>
                </grid-layout>
            </el-row>
            <el-row class="row-in-grid-item">
                <span>{{ templateInfo.infoRemark }}</span>
            </el-row>
        </div>
    </div>
</template>

<script>
import diagnosisDefault from '@templates/diagnosisDefault';
import _ from 'lodash';
import VueGridLayout from 'vue-grid-layout';
export default {
    name: 'DiagnosisReportView',
    components: {
        GridLayout: VueGridLayout.GridLayout,
        GridItem: VueGridLayout.GridItem,
    },
    data() {
        return {
            showPrintBtns: true,
            htmlTitle: '病理咨询意见书',
            imageServiceURL: process.env.ImageServiceURL,
            diagnosis: diagnosisDefault,
            isFinished: false,
            // 检查类型
            checkCategory: '',
            // 病理切片数据
            annotationList: [],
            // 诊断意见数据
            opinionJson: {},
            // 模板布局列数
            templateCol: 12,
            // 模板信息
            templateInfo: {
                id: 0,
                updateTime: '',
                infoImageUrl: '',
                infoInstitutionName: '',
                infoTitle: '',
                infoWatermark: '',
                infoRemark: '备注：',
            },
            // 模板组件列表
            componentList: [],
            currentTime: '',
        };
    },
    mounted() {
        this.getNowTime();
        this.diagnosisRequest();
    },
    computed: {
        pathologyId() {
            return this.$route.params.pid;
        },
        userId() {
            return this.$route.params.uid;
        },
    },
    methods: {
        getNowTime() {
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf =
                new Date().getMinutes() < 10
                    ? '0' + new Date().getMinutes()
                    : new Date().getMinutes();
            let ss =
                new Date().getSeconds() < 10
                    ? '0' + new Date().getSeconds()
                    : new Date().getSeconds();
            this.currentTime =
                yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
        },
        toPrint() {
            this.showPrintBtns = false;
            setTimeout(() => {
                window.print();
                this.showPrintBtns = true;
            }, 100);
        },
        async diagnosisRequest() {
            const res = await this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/diagnosis/single',
                params: {
                    pathologyId: this.pathologyId,
                },
            });

            if (res && res.data.code === 200) {
                const result = res.data.data;
                if (result.currentLevel !== 6) {
                    this.isFinished = false;
                    return;
                }
                this.isFinished = true;
                result.cardId = result.cardId != null ? result.cardId : '';

                // 基础信息处理
                Object.keys(this.diagnosis).forEach((key) => {
                    if (typeof this.diagnosis[key] === 'string') {
                        this.diagnosis[key] = _.get(result, key, '');
                    } else if (typeof this.diagnosis[key] === 'number') {
                        this.diagnosis[key] = _.get(result, key, 0);
                    } else if (this.diagnosis[key] instanceof Array) {
                        this.diagnosis[key] = _.clone(result[key]);
                    } else if (this.diagnosis[key] instanceof Object) {
                        this.diagnosis[key] = _.get(result, key, { name: '' });
                    } else {
                        this.diagnosis[key] = _.get(result, key, '');
                    }
                    if (this.diagnosis[key] === null) {
                        this.diagnosis[key] = '';
                    }
                });

                // 取材脏器名字获取
                this.diagnosis.sampleOrganName = _.get(
                    this.diagnosis.sampleOrganOrgan,
                    'name',
                    ''
                );
                // 年龄
                this.diagnosis.ageAll = `${this.diagnosis.age}${this.diagnosis.ageUnitName}`;
                // 诊断意见数据格式化
                this.diagnosis.diagnosisDetailList.forEach((t) => {
                    if (
                        t.currentLevel === this.diagnosis.prevLevel &&
                        t.detailString
                    ) {
                        const detailString = t.detailString.replace('\\', '');
                        this.opinionJson = JSON.parse(detailString);
                    } else {
                        this.opinionJson = {};
                    }
                });

                this.checkCategory = this.diagnosis.checkCategory;
                console.log('this.diagnosis', this.diagnosis);
                this.reportTemplateRequest();
            }
        },
        async reportTemplateRequest() {
            const res = await this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/report-templates/check-category',
                params: {
                    checkCategory: this.checkCategory,
                },
            });

            if (res && res.data.code === 200) {
                const result = res.data.data;
                // 报告模板列数
                this.templateCol = _.get(result, 'settingsColNum', 12);
                // 报告模板基础数据
                Object.keys(this.templateInfo).forEach((key) => {
                    this.templateInfo[key] = result[key];
                });
                // 报告模板组件
                this.componentList = [];
                result.reportTemplateComponents.forEach((t, index) => {
                    const item = t;
                    item.index = index;
                    this.componentList.push(item);
                });
                this.baseInfoInit();
                this.annotationListInit();
            }
        },
        baseInfoInit() {
            this.componentList.forEach((t, index) => {
                if (t.bigType === 'base') {
                    const key = t.i.split('_')[2];
                    this.componentList[index].stringContent += _.get(
                        this.diagnosis,
                        key,
                        ''
                    );
                }
            });
        },
        annotationListInit() {
            this.diagnosis.biopsyList.forEach((biopsy) => {
                const { annotationsList } = biopsy;
                if (annotationsList) {
                    annotationsList.forEach((t) => {
                        this.annotationList.push({
                            imgUrl: this.imageServiceURL + t.imgUrl,
                        });
                    });
                }
            });
        },
        styleString(styleJson) {
            let style = 'width: 100%; word-break:break-all;';
            Object.keys(styleJson).forEach((key) => {
                style += `${key}:${styleJson[key]};`;
            });
            return style;
        },
        OpenImage(herf) {
            const width = window.screen.availWidth + 10;
            const height = window.screen.availHeight + 10;
            window.open(
                herf,
                '_blank',
                `location=no,width=${width},height=${height}`
            );
        },
    },
};
</script>

<style scoped>
.btns {
    position: absolute;
    top: 10px;
    right: 50px;
}

.diagnose-img {
    max-height: 100px;
    max-width: 120px;
    margin-left: 12px;
}
/* Custom container */
.container-narrow {
    margin: 0 auto;

    max-width: 750px;

    height: max-content;

    background: #ffffff;

    padding: 20px;
}

hr {
    margin: 0;
    border: 0;
    border-top: 1px solid #000;
    border-bottom: 1px solid #000;
}

h1,
h2,
h3,
h4,
h5,
h6 {
    margin: 0 0;
}

h3 {
    font-size: 25px;
    font-weight: 900;
}

h4 {
    font-size: 18px;
    font-weight: 900;
}

h5 {
    font-size: 16px;
    font-weight: 900;
}

.text-mini {
    font-size: 12px;
}

.row-in-grid-item {
    min-height: 24px;

    display: flex;

    align-items: center;
}
.watermark-div {
    position: fixed;

    width: 750px;

    margin-top: 10px;
}
.watermark {
    opacity: 0.3;
    z-index: 99;
    color: gray;
    font-size: 20px;
    width: 185px;
    height: 80px;
    transform: rotate(-20deg);
    float: left;
}
</style>
